<?php

namespace App\Http\Controllers\Admin;

use App\Models\MemberOther;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Response as SymfonyResponse;

class ExtensionStatisticsController
{
    private $oneITime = 1; // 单位时间 一分钟
    private $oneIMax = 10; // 一个用户Ip一分钟最多仅允许访问访问10次

    private $platITime = 10; // 针对所有用户，单位时间内允许访问的最大次数
    private $platIMax = 1000; // 针对所有的用户,该接口最多仅允许访问N次




    public function handle(Request  $request)
    {
        $redis = new \redis();
        $userid = $_SERVER['HTTP_USER_AGENT'];
        $redis->connect("127.0.0.1");
        $redis->select(0);
        //.... 针对平台全局锁，用于限制单位时间内所有用户访问的次数
        $platKey = md5($request->path());

        $platFlowCount = $redis->get($platKey);// 平台访问次数
        $ttl = $redis->ttl($platKey);

        $ip=$request->getClientIp();

        $content = [
            'request'=>json_encode(['sale_user_id'=>$request['sale_user_id']??0,'ip'=>$ip,'create_time'=>time()]),
        ];
     \Illuminate\Support\Facades\Log::info('推广访问统计',$content);

        if ($ttl <= 0) {
           $redis->del($platKey);
            $platFlowCount=0;
        }

        if($platFlowCount){
            if($platFlowCount >= $this->platIMax){
                return Response::json("平台超过限制",SymfonyResponse::HTTP_LOCKED,[],256);
            }
        }
        $redis->incr($platKey);// ++1 次访问次数
        !$platFlowCount && $redis->expire($platKey,$this->platITime); // 设置锁的有效时间


        // ... 针对单个用户实现的访问锁
        $key = md5($ip.":".$userid);
        // 实现一个用户一分钟最多允许访问10次
        $userFlowCount = $redis->get($key); // 单个用户访问次数

        $ttl = $redis->ttl($key);
        if ($ttl <= 0) {
            $redis->del($key);
            $userFlowCount=0;
        }

        if($userFlowCount){
            if($userFlowCount >= $this->oneIMax){
                return Response::json("用户访问超过限制",SymfonyResponse::HTTP_LOCKED,[],256);
            }
        }
        $redis->incr($key);// ++1 次访问次数
        !$userFlowCount && $redis->expire($key,$this->oneITime);//设置锁的有效时间

        Db::table('sp_extension_statistics')->insert(['sale_user_id'=>$request['sale_user_id']??0,'ip'=>$ip,'http_user_agent'=>$userid,'create_time'=>time()]);
        return Response::json(['status'=>200,'msg'=>'ok']);

    }

}
